package com.startupwebapp.web.controller;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.startupwebapp.core.domain.users.Person;
import com.startupwebapp.core.domain.users.PersonRole;
import com.startupwebapp.services.PersonService;

@Controller
@RequestMapping("/person.html")
public class PersonController {
	private static boolean DEFAULT_ACTIVE_STATE = true;
	@Autowired
	private PersonService personService;

	// @Autowired
	// private RoleService roleService;

	@ModelAttribute
	public List<Person> loadAllPersons() {
		return personService.findByActiveState(DEFAULT_ACTIVE_STATE);
	}

	@RequestMapping(method = RequestMethod.GET)
	protected String addPersonBackingObjectToModel(Model model) {

		model.addAttribute("person", new Person());
		return "person";
	}

	@RequestMapping(params = { "control=OK" }, method = RequestMethod.POST)
	protected String savePerson(@ModelAttribute("person") Person person) {
		person.setRoles(Arrays.asList(new PersonRole[] { PersonRole.USER }));
		personService.savePerson(person);
		return "person";
	}

	@RequestMapping(params = "change", method = RequestMethod.GET)
	public String changeState(@RequestParam("change") Integer personId) {
		// TODO: parse input params instead of using true
		personService.setPersonState(personId, true);
		return "redirect:managePersons.html?first=0&amount=10";
	}

	@RequestMapping(params = { "control=Cancel" }, method = RequestMethod.POST)
	protected String onSubmitChangeRoleCancel() {
		return "redirect:managePersons.html?first=0&amount=10";
	}

}
